<?php

namespace App\Common\Cla\Web;

use App\Common as com;

class PasswordHash extends com\Cla\ClaBase {

	/**
	 * 明文密码
	 * @var string
	 */
	private string $password;

	/**
	 * 加密盐
	 * @var string
	 */
	private string $saltKey;

	/**
	 * Hash constructor.
	 * @param string $password 明文密码
	 * @param string $saltKey 加密盐
	 */
	public function __construct( string $password, string $saltKey = '' ) {
		// ...
		if( empty( $password ) ){
			throw com\Lib\Err\Exception::makeOfNew( '参数->密码不能为空' );
		}
		//
		$this->password = $password;
		$this->saltKey = $saltKey;
		//
		parent::__construct();
	}

	/**
	 * 验证PasswordHash
	 * @param string $passwordHash 待验证hash
	 * @return bool [true]验证通过 [false]验证不通过
	 */
	public function verify( string $passwordHash ):bool {
		return password_verify( $this->buildPasswordHash(), $passwordHash );
	}

	/**
	 * 生成PasswordHash
	 * @return string
	 */
	public function buildHash():string {
		return password_hash( $this->buildPasswordHash(), PASSWORD_BCRYPT );
	}

	/**
	 * 生成密码hash
	 * @return string
	 */
	private function buildPasswordHash():string {
		return md5( md5( $this->password ) . md5( $this->saltKey ) . com\Cla\Web::getWebSaltKey() );
	}

	// ===============================
	//
	//
	// 下面为静态方法
	//
	//
	// ===============================

	/**
	 * 快速获取密码Hash
	 * @param string $password 明文密码
	 * @param string $saltKey 加密盐
	 * @return string
	 */
	public static function getPasswordHash( string $password, string $saltKey = '' ):string {
		return ( new static( $password, $saltKey ) )->buildPasswordHash();
	}

}
